import {DirTree} from "@/utils/main/file.uitls";
import {IpcRenderer} from "@/utils/render/common";
import {findInTree} from "@/utils/array.utils";
import store from "@/store";

const state = {
    notes: [] as DirTree[],
    noteDirectories: [] as DirTree[],
    selectedNote: null as DirTree,
    selectedFolder: null as DirTree,
    selectedItem: null as DirTree,

    gitSync: false,
}

const mutations = {}

const actions = {

    // 同步笔记本
    async syncNotes({dispatch, state}) {
        state.notes = await IpcRenderer.invoke("getNotes");
        dispatch('setSelectedNote');
    },

    // 同步笔记本目录
    async syncNoteDirectories({dispatch, state}) {
        if (!state.selectedNote) state.noteDirectories = [];
        else {
            state.noteDirectories = await IpcRenderer.invoke("getNoteDirectories", state.selectedNote.name);
        }
        dispatch("setSelectedFolder");
    },

    // 设置被选笔记
    setSelectedNote({dispatch, state, commit}, note) {
        try {
            const config = store.state['application'].config;
            if (note !== undefined) return state.selectedNote = note;
            if (!state.notes.length) return state.selectedNote = null;
            if (!state.selectedNote && config.selectedNoteName) {
                const nt = state.notes.find(item => item.name === config.selectedNoteName)
                if (nt) return state.selectedNote = nt;
            }
            if (!state.selectedNote) return state.selectedNote = state.notes[0];
            const sn = state.notes.find(nt => nt.key === state.selectedNote.key);
            if (sn) return state.selectedNote = sn;
            state.selectedNote = state.notes[0];
        } finally {
            setTimeout(() => {
                commit("setConfig", {config: {selectedNoteName: state.selectedNote ? state.selectedNote.name : ''}});
                setTimeout(() => {
                    IpcRenderer.invoke("pullNote");
                }, 1000);
            })
            dispatch('syncNoteDirectories');
        }
    },

    // 设置被选中的文件夹
    setSelectedFolder({state}, folder) {
        if (folder !== undefined) return state.selectedFolder = folder;
        if (state.selectedFolder) {
            const res = findInTree(state.noteDirectories, (item: DirTree) => item.key === state.selectedFolder.key);
            if (res) return state.selectedFolder = res;
        }
        state.selectedFolder = state.selectedNote;
    },

    // 设置被选内容
    setSelectedItem({state}, item) {
        if (item !== undefined) state.selectedItem = item;
    },

    // 设置 git 同步状态
    setGitSync({state, dispatch}, status: boolean) {
        state.gitSync = status;
    }
}

const getters = {}

export default {
    state, mutations, actions, getters
}